// pages/list/list.js
var app = getApp()
var network = require("../../api/api.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabScrollTop: 0,
    tabFixed: false,
    lastX: 0,     //滑动开始x轴位置
    lastY: 0,     //滑动开始y轴位置
    text: "没有滑动",
    currentGesture: 0, //标识手势
    // checkedColor: '#52a4f8',
    checkedColor:'#ffffff',
    isAgree: false,
    scrollTop: 100,
    page_index: '1',
    current_page: 1,
    query: {},
    answer: [],
    already_answer: [],
    total_page: 1,
    total_number: 0,
    already_number: 0,
    user_id: '',
    time_limit: 90,
    timeTxt: '',
    doneNum: 0,
    allNum: 0,
  },
  handletouchmove: function (event) {
    var currentX = event.touches[0].pageX
    var currentY = event.touches[0].pageY
    var tx = currentX - this.data.lastX
    var ty = currentY - this.data.lastY
    var text = ""
    //左右方向滑动
    if (Math.abs(tx) > Math.abs(ty)) {
      if (tx < 0)
        text = "向左滑动"
      else if (tx > 0)
        text = "向右滑动"
    }
    //上下方向滑动
    else {
      if (ty < 0)
        text = "向上滑动"
      else if (ty > 0)
        text = "向下滑动"
    }

    //将当前坐标进行保存以进行下一次计算
    this.data.lastX = currentX
    this.data.lastY = currentY
    this.setData({
      text: text,
    });
  },

  //滑动开始事件
  handletouchtart: function (event) {
    this.data.lastX = event.touches[0].pageX
    this.data.lastY = event.touches[0].pageY
  },
  //滑动结束事件
  handletouchend: function (event) {
    this.data.currentGesture = 0;
    this.setData({
      text: "没有滑动",
    });
  },
  bindAgreeChange: function (e) {
    this.setData({
      isAgree: !!e.detail.value.length
    });
  },
  checkboxChange: function (e) {
    const type_of = typeof e.detail.value
    let item = e.target.dataset.item
    // 已经答题过了，再次查看的时候
    if (item.answer_status === '0') {
      return false;
    }
    let answer_list = item.answer_list
    let answer = this.data.answer;
    let already_item = {}
    let result = {}
    let rightCount = 0
    let already_answer = this.data.already_answer
    already_item.question_id = item.question_id
    // 如果选择的答案正确则为1，否则为0
    if (type_of === 'string') {
        const radio_result = answer_list.find(v => v.answer_id.toString() === e.detail.value)
        already_item.result = radio_result.result
    } else {
        // answer_list.forEach(v => {
        //     let idx = e.detail.value.indexOf(v.answer_id.toString())
        //     // 多选判断答案是否正确
        //     if (v.result === 1 && idx >= 0) {
        //         rightCount += 1
        //     }
        // })
        // already_item.result = rightCount === e.detail.value.length && e.detail.value.length > 0 ? 1 : 0
        const correct = answer_list.filter(v => {
          return v.result
        })
        const correctList = correct.map(v => {
            return v.answer_id.toString()
        })
       const errorList = e.detail.value.filter(v => {
         return correctList.indexOf(v) === -1
       })
        already_item.result = !errorList.length && e.detail.value.length === correctList.length ? 1 : 0;
    }
      already_item.answer_ids = type_of === 'string' ?  e.detail.value : e.detail.value.join(',')
    answer_list = answer_list.map(v => {
      return {
        answer_id: v.answer_id,
        name: v.name,
        result: v.result,
        checked: type_of === 'string' ? e.detail.value === v.answer_id.toString() : e.detail.value.indexOf(v.answer_id.toString()) >= 0
      }
    })
    item.answer_list = answer_list
    answer = answer.map(v => {
      return v.question_id === item.question_id ? item : v
    })
    const already_filter = already_answer.find(v => v.question_id === already_item.question_id)
    if (already_filter) {
      const index = already_answer.indexOf(already_filter)
      already_answer[index] = already_item
    } else {
      already_answer.push(already_item)
    }
    this.setData({
      already_answer: already_answer
    })
    this.setData({
      answer: answer
    })
  },
  getAnswer: function () {
    const that = this
    var params = new Object()
    params.business_param = {}
    params.common_param = {}
    params.business_param.paper_id = this.data.query.paper_id
    params.business_param.user_paper_id = this.data.query.user_paper_id
    params.business_param.groups_id = this.data.query.groups_id
    params.common_param.page_index = this.data.page_index
    params.common_param.page_size = '5'
    params.common_param.is_paging = '1'
    params.common_param.is_couting = '1'
    network.POST({
      params: params,
      url: "get_answer_list",
      success: function (res) {
        const total_number = Number(res.common_param.total_number)
        const page_size = 5
        let resultList = res.result
          let filterResult = []
          resultList  = resultList.map(v => {
              filterResult = v.answer_list.filter(val => {
              return !!val.result
            })
            v.isRadio = filterResult.length === 1
            return v
          })
        that.setData({
          answer: resultList
        })
        that.setData({
          page_index: String(parseInt(res.common_param.page_index) + 1)
        })
        that.setData({
          current_page: Number(res.common_param.page_index)
        })
        that.setData({
          total_page: Math.ceil(total_number / page_size)
        })
        // that.setData({total_number: total_number})
        //拿到解密后的数据，进行代码逻辑

      },
      fail: function () {
        //失败后的逻辑

      },
    })
  },

  nextPage: function () {
    var that = this
    // 如果是再次进入查看试卷的情况
    if (this.data.already_answer.length === 0) {
      that.get_paper_info();
      that.getAnswer.apply(that)
    } else {
      this.submit_answer(function () {
        that.get_paper_info();
        that.getAnswer.apply(that)
      })
    }
  },

  finish_answer: function () {
    if (this.data.already_answer.length === 0) {
      wx.navigateBack({
        delta: 1
      })
      return
    }
    this.submit_answer(function () {
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2];
      prevPage.setData({
        already_groups: ++prevPage.data.already_groups
      })
      wx.navigateBack({
        delta: 1
      })
    })
  },

  submit_answer: function (callback) {
    const that = this

    var userLogin = wx.getStorageSync('user_login') || {}
    var params = new Object()
    params.business_param = {}
    params.business_param.user_id = String(userLogin.user_id)
    params.business_param.paper_id = this.data.query.paper_id
    params.business_param.user_paper_id = this.data.query.user_paper_id
    params.business_param.groups_id = this.data.query.groups_id
    params.business_param.submit_status = 1
    params.business_param.submit_type = 1
    params.business_param.answer_list = this.data.already_answer
    network.POST({
      params: params,
      url: "submit_answer_list",
      success: function (res) {
        that.setData({
          already_answer: []
        })
        callback && callback()
        //拿到解密后的数据，进行代码逻辑

      },
      fail: function () {
        //失败后的逻辑

      },
    })
  },
  setTimer: function (m) {
    let that = this;
    let ts = m;
    let tid = 'tid';
    let timer = function (id) {
      if (ts > 0) {
        var hh = parseInt(ts / 60 / 60 % 24, 10);
        var mm = parseInt(ts / 60 % 60, 10);
        var ss = parseInt(ts % 60, 10);
        hh = hh < 10 ? ("0" + hh) : hh; //时
        mm = mm < 10 ? ("0" + mm) : mm; //分
        ss = ss < 10 ? ("0" + ss) : ss; //秒
        const setTimeOutList = setTimeout(function () {
          timer(id);
        }, 1000);
        ts -= 1;
        that.setData({
          timeTxt: hh + ':' + mm + ':' + ss,
            setTimeOutList: setTimeOutList
        })
      } else {
        that.setData({
          timeTxt: '00:00:00'
        })
        that.finished_paper()
      }
    }
    timer(tid);
  },
  // 获取显示参数
  get_paper_info() {
    const that = this
    var params = new Object()
    params.business_param = {}
    params.business_param.user_id = String(this.data.user_id)
    params.business_param.paper_id = this.data.query.paper_id
    params.business_param.user_paper_id = this.data.query.user_paper_id
    params.business_param.submit_status = 1
    params.business_param.submit_type = 1
    params.business_param.answer_list = this.data.already_answer
    network.POST({
      params: params,
      url: "get_paper_info",
      success: function (res) {
        const result = res.result[0]
        that.setTimer(result.live_time_limit - 0)
        that.setData({
          already_number: result.done_questions_num - 0,
          total_number: result.questions_num - 0
        })
        //拿到解密后的数据，进行代码逻辑
      },
      fail: function () {
        //失败后的逻辑
      },
    })
  },
  finished_paper() {
    const that = this
    var params = new Object()
    params.business_param = {}
    params.business_param.user_id = String(this.data.user_id)
    params.business_param.paper_id = this.data.query.paper_id
    params.business_param.user_paper_id = this.data.query.user_paper_id
    params.business_param.submit_status = 1
    params.business_param.submit_type = 1
    params.business_param.answer_list = this.data.already_answer
    network.POST({
      params: params,
      url: "finished_paper",
      success: function (res) {
        const result = JSON.stringify(res.result[0])
        wx.navigateTo({
          url: `../resu/resu?result=${result}&paper_id=${that.data.query.paper_id}&user_paper_id=${that.data.query.user_paper_id}`
        })
        //拿到解密后的数据，进行代码逻辑
      },
      fail: function () {
        //失败后的逻辑
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userLogin = wx.getStorageSync('user_login') || {};
    var time_limit = wx.getStorageSync('time_limit') || 90;
    this.setData({
      query: options,
      user_id: userLogin.user_id,
      time_limit: time_limit
    })
    this.getAnswer()
    this.get_paper_info()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      if (this.data.setTimeOutList) {
          clearTimeout(this.data.setTimeOutList)
      }
      this.setData({
          setTime: 1
      })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})